﻿using AntdUI;
using ClosedXML.Excel;
using Serilog;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using WorkTool2.Classes.Data;
using WorkTool2.Helpers;
using WorkTool2.Interfaces;

namespace WorkTool2.Controls
{
    public partial class WorkMonthlyReport : UserControl, IReload
    {
        private Form form;

        public WorkMonthlyReport(Form _form)
        {
            form = _form;
            InitializeComponent();
        }

        public void Reload()
        {
            tree.Items.Clear();
            foreach (var workMonthlyReportSetting in SettingsHelper._workMonthlyReportSettings.Project)
            {
                var it = new TreeItem(workMonthlyReportSetting.ProjectName);
                foreach (var project in workMonthlyReportSetting.ProjectGit)
                {
                    it.SetSub(new TreeItem(Path.GetFileName(project.ProjectPath.TrimEnd('\\'))).SetSubTitle(project.Branch));
                }
                tree.Items.Add(it);
            }
            tree.ExpandAll();
        }

        protected override void OnLoad(EventArgs e)
        {
            try
            {
                base.OnLoad(e);
                ITask.Run(() =>
                {
                    Reload();
                    steps.Current = -1;
                    table.Columns = [];
                    var properties = typeof(WorkMonthlyReportResult).GetProperties(BindingFlags.Public | BindingFlags.Instance);
                    foreach (var property in properties)
                    {
                        var descriptionAttr = property.GetCustomAttribute<DescriptionAttribute>();
                        if (descriptionAttr != null)
                        {
                            table.Columns.Add(new Column(property.Name, descriptionAttr.Description, ColumnAlign.Center).SetEllipsis().SetMaxWidth("50%"));
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                Log.Error(ex, ex.Message);
            }
        }

        private Table.CellStyleInfo? table_SetRowStyle(object sender, TableSetRowStyleEventArgs e)
        {
            if (e.Index % 2 == 0)
            {
                return new Table.CellStyleInfo
                {
                    BackColor = Color.WhiteSmoke
                };
            }
            return null;
        }

        private void select_SelectedValueChanged(object sender, ObjectNEventArgs e)
        {
            datePicker.Visible = e.Value.ToString() == "自定义";
        }

        private void button_Click(object sender, EventArgs e)
        {
            Spin.open(form, "正在处理中，请耐心等候...",
                 config =>
                {
                    try
                    {
                        steps.Current = -1;
                        DateTime? date = null;
                        switch (select.SelectedIndex)
                        {
                            case 0:
                                break;

                            case 1:
                                date = DateTime.Now;
                                break;

                            case 2:
                                date = DateTime.Now.Date.AddMonths(-1);
                                break;

                            case 3:
                                if (string.IsNullOrEmpty(datePicker.Text.Trim()))
                                {
                                    Modal.open(form, "错误", "请选择或输入要查询的月份", TType.Error);
                                    return;
                                }
                                date = DateTime.Parse(datePicker.Text.Trim());
                                break;

                            default:
                                Modal.open(form, "错误", "请选择或输入要查询的月份", TType.Error);
                                return;
                        }
                        steps.Current++;
                        var worksheetName = "all";
                        var worksheet1Name = "next month";
                        string? startDate = null;
                        string? endDate = null;
                        if (date.HasValue)
                        {
                            var startMonth = date.Value.AddDays(1 - date.Value.Day);
                            worksheetName = $"{ToolHelper._month[startMonth.ToString("MM")]}.,{startMonth:yyyy}";
                            startDate = startMonth.ToString("yyyy-MM-dd");
                            endDate = startMonth.AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
                            var nextMonth = startMonth.AddMonths(1);
                            worksheet1Name = $"Plan_{ToolHelper._month[nextMonth.ToString("MM")]}.,{nextMonth:yyyy}";
                        }
                        var reportList = new List<WorkMonthlyReportResult>();
                        var nextMonthList = new List<WorkMonthlyReportResult>();
                        steps.Current++;
                        foreach (var projects in SettingsHelper._workMonthlyReportSettings.Project)
                        {
                            foreach (var item in projects.ProjectGit)
                            {
                                config.Text = $"正在获取项目【{projects.ProjectName} -> {Path.GetFileName(item.ProjectPath.TrimEnd('\\'))}】分支【{item.Branch}】的提交信息...";
                                var (IsSuccess, Message) = GitHelper.ExecuteGitCommand("fetch", item.ProjectPath);
                                if (!string.IsNullOrWhiteSpace(Message))
                                    Log.Error($"[git fetch]{Message}");
                                var (Data, ErrorMessage) = GitHelper.GetGitCommit(item.Branch, SettingsHelper._workMonthlyReportSettings.Author, item.ProjectPath, startDate, endDate);
                                if (!string.IsNullOrWhiteSpace(ErrorMessage))
                                {
                                    Modal.open(form, "错误", $"获取项目【{projects.ProjectName} -> {Path.GetFileName(item.ProjectPath.TrimEnd('\\'))}】分支【{item.Branch}】的提交信息失败\n\t错误信息：\n\t{ErrorMessage}", TType.Error);
                                    continue;
                                }
                                config.Text = $"正在处理项目【{projects.ProjectName} -> {Path.GetFileName(item.ProjectPath.TrimEnd('\\'))}】分支【{item.Branch}】的数据...";
                                foreach (var data in Data)
                                {
                                    if (!reportList.Any(x => x.CompletedJobs.Equals(data.Message)))
                                    {
                                        reportList.Add(new WorkMonthlyReportResult
                                        {
                                            BU = SettingsHelper._workMonthlyReportSettings.BU,
                                            EnglishName = SettingsHelper._workMonthlyReportSettings.EnglishName,
                                            ChineseName = SettingsHelper._workMonthlyReportSettings.ChineseName,
                                            StaffCode = SettingsHelper._workMonthlyReportSettings.StaffCode,
                                            ProjectName = projects.ProjectName,
                                            ProjectCode = projects.ProjectCode,
                                            CompletedJobs = data.Message
                                        });
                                    }
                                }
                            }
                            nextMonthList.Add(new WorkMonthlyReportResult
                            {
                                BU = SettingsHelper._workMonthlyReportSettings.BU,
                                EnglishName = SettingsHelper._workMonthlyReportSettings.EnglishName,
                                ChineseName = SettingsHelper._workMonthlyReportSettings.ChineseName,
                                StaffCode = SettingsHelper._workMonthlyReportSettings.StaffCode,
                                ProjectName = projects.ProjectName,
                                ProjectCode = projects.ProjectCode
                            });
                        }
                        table.DataSource = reportList;
                        steps.Current++;
                        steps.Current++;
                        config.Text = "正在生成Excel文件...";
                        using var workbook = new XLWorkbook(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "WorkMonthlyReportTemplate.xlsx"));
                        var worksheet = workbook.Worksheet(1);
                        worksheet.Name = worksheetName;
                        worksheet.Cell(3, 1).InsertData(reportList);
                        var worksheet1 = workbook.Worksheet(2);
                        worksheet1.Name = worksheet1Name;
                        worksheet1.Cell(3, 1).InsertData(nextMonthList);
                        var filePath = Path.Combine(SettingsHelper._fileSettings.SaveFolder, $"Monthly Project Report_{worksheetName}_{SettingsHelper._workMonthlyReportSettings.EnglishName}{(SettingsHelper._fileSettings.SaveFileNameRandom ? $"_{new Random().Next(10000, 99999)}" : "")}.xlsx");
                        workbook.SaveAs(filePath);
                        steps.Current++;
                        steps.Current++;
                        config.Text = "";
                        if (new Modal.Config(form, "是否打开文件？", $"文件已保存至：{filePath}", TType.Success)
                        {
                            OnButtonStyle = (id, btn) =>
                            {
                                btn.BackExtend = "135, #6253E1, #04BEFE";
                            },
                            CancelText = "否",
                            OkText = "是"
                        }.open() == DialogResult.OK)
                        {
                            Process.Start(new ProcessStartInfo
                            {
                                FileName = filePath,
                                UseShellExecute = true
                            });
                        }
                        (form as Main).AddHistoryData(new HistoryData("工作月报表", filePath)).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        Notification.error(form, "生成报表失败", ex.Message, AntdUI.TAlignFrom.Top);
                        Log.Error(ex, ex.Message);
                    }
                },
                () => { }
            );
        }
    }
}